<script setup>
import { onLoad, onShow } from '@dcloudio/uni-app';
import { onMounted } from 'vue';
import { ref } from 'vue';
import { clothesChangeClothesApi } from "@/apis/clothes.js"
import { useUserStore } from "@/stores/userStore.js"
const props = defineProps({
  list: Array,
  bgUrl: String,
})
const emits = defineEmits(['base64']);
let socketTask = null
const userStore = useUserStore()
const change = async (item) => {
  const userInfo = userStore.getUserInfo()
  // 把当前点击的图片 和 userId传入后端，后端根据id获取用户的CGURL，然后进行替换操作，返回base64给前端
  // const res = await clothesChangeClothesApi({'imageUrl':item.localUrl,'bgUrl':props.bgUrl, 'cgId':'CG'+userInfo.userId})
  // console.log(res);
   // 创建WebSocket连接
   socketTask = uni.connectSocket({
      url: 'ws://127.0.0.1:6999/change',
      success: () => {}
  });
  // 监听WebSocket连接打开事件
  socketTask.onOpen( async() => {
      uni.onSocketMessage((res) => {
        const base64 = JSON.parse(res.data)[0].base64
        if (base64) {
          emits('base64', base64);
          socketTask.close({
            code: 1000, // 关闭连接的状态码，默认值1000，表示正常关闭
            reason: '关闭连接', // 关闭的原因，可选
            success: () => {
            },
          });
        }
      })
      socketTask.send({
        data:JSON.stringify({'imageUrl':item.localUrl,'bgUrl':props.bgUrl, 'cgId':'CG'+userInfo.userId })
      });
  });

}

onLoad(() => {
})

</script>
<template>
  <div class="body">
    <div class="container">
      <!-- 一个个方框 -->
      <uni-swipe-action>
        <div class="single-img" v-for="(item,index) in list" :key="index" @click="change(item)">
          <uni-swipe-action-item
          :right-options="options"
          :left-options="options"
          >
            <img :src="item.imageUrl" class="image"/>
          </uni-swipe-action-item>
        </div>
      </uni-swipe-action>
    </div>
  </div>
</template>
<style scoped lang="scss">
.image {
  max-width: 100%;
  max-height: 100%;
  height: 50px;
  width: 100%;
  border-radius: 5rpx;
  $uni-shadow-base:0 1px 8px 1px rgba($color: #a5a5a5, $alpha: 0.2);
}
</style>
